<template>
  <div class="page memberManage" v-if="isOpen">
    <filterItem
      ref="memberManageFilterItem"
      @filterChoice="handleFilterChoice"
      :roleInfo="roleInfo"
      :currentStore="currentStore"
    ></filterItem>
    <memberManageDetails ref="memberManageDetails" :params="detailsParams"></memberManageDetails>
    <div class="scroll-view">
      <customHeader
        middleTitle="会员管理"
        @leftCallBack="goBack"
        @rightCallBack="handleAnalysis"
        @rightCallBack2="handleClickFilter"
      >
        <i class="zhk-hyfx"></i>
        <div slot="slot2">
          <i class="filter-icon zhk-nav_filter" :class="{blue:searchParam.shopId}"></i>
        </div>
      </customHeader>
      <searchBar @search="searchCallbck" placeholder="请输入昵称/手机号" />
      <div class="page-body">
        <div class="section" ref="wrapper" :style="{ height:'100%' }">
          <no-data msg="暂无会员" v-if="list.length==0"></no-data>
          <ul
            class="list"
            v-infinite-scroll="loadMore"
            infinite-scroll-disabled="loading"
            infinite-scroll-distance="30"
            v-show="list.length>0"
          >
            <li v-for="(item,index) in list" :key="index" @click="linkToDetail(item)">
              <div class="left">
                <img :src="avatar(item.avatar)" alt />
              </div>
              <div class="right-data">
                <div class="member-name">{{item.nickName?item.nickName:"匿名"}}</div>
                <div class="middle">
                  <div class="level">
                    <i class="zhk-hydj"></i>
                    <span>{{item.customerGradeName}}</span>
                  </div>
                  <div class="gender">
                    <i class="zhk-xb-n" v-if="item.gender==1"></i>
                    <i class="zhk-xb-nv" v-if="item.gender==2"></i>
                  </div>
                </div>
                <div class="mobile">{{item.phone?item.phone:"未绑定"}}</div>
              </div>
            </li>
          </ul>
          <p v-show="loading" class="page-infinite-loading">
            <mt-spinner :style="{display:'inline-block'}" type="fading-circle"></mt-spinner>
          </p>
          <div v-show="noMore&&!loading&&role!==''&&list.length!==0" class="no-more">
            <span>已经全部加载完毕</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import customHeader from "../../components/header/header";
import searchBar from "../../components/searchBar/searchBar";
import memberManageDetails from "../memberManage/details";
import jsBridge from "../../tools/jsBridge.js";
import { Search, Toast, MessageBox } from "mint-ui";
import noData from "../../components/noData/noData";
import filterItem from "./filterItem";
export default {
  name: "memberManage",
  data() {
    return {
      currentStore: [{ selectKey: "", selectName: "" }],
      loading: false,
      noMore: false,
      pageIndex: 1,
      pageSize: 10,
      totalCount: 0,
      isOpen: false,//是否订购过会员服务
      list: [],
      role: "",
      roleInfo: {},
      selfShopId: "",
      filterData: {
        channelSource: "",
        gender: "",
        store: "",
        shopName: "",
        shopId: "",
      },
      searchParam: {
        id: ""
      },
      detailsParams: null
    };
  },
  methods: {
    avatar(url) {
      if (url) {
        return url;
      } else {
        return require(`../../../static/images/member_avatar.png`);
      }
    },
    searchCallbck(v) {
      this.searchParam.id = v;
      this.pageIndex = 1;
      this.loadData();
    },
    linkToDetail(item) {
      this.detailsParams = item;
      this.$refs.memberManageDetails.popupShow();
    },
    tradeTimeFormate(tradeTime) {
      return CommonUtil.timestampToTime(tradeTime);
    },
    //打开筛选
    handleClickFilter() {
      this.$refs.memberManageFilterItem.popupShow();
    },
    handleAnalysis() {
      this.$router.push({ path: "/memberManage/memberAnalysis" });
    },
    //筛选确定
    handleFilterChoice(v) {
      const store = this.filterData.store;
      this.filterData = v;
      if (v.store.length === 0) {
        this.filterData.store = store;
      } else {
        this.filterData.shopId = v.store[0].selectKey;
        this.filterData.shopName = v.store[0].selectName;
      }
      this.filterData.channelSource = v.payTypeList.length > 0 ? Number(v.payTypeList[0].value) : "";
      this.filterData.gender = v.genderList.length > 0 ? Number(v.genderList[0].value) : "";
      this.pageIndex = 1;
      this.loadData();
    },
    goBack() {
      if (this.$refs.memberManageDetails.popupVisible) {
        this.$refs.memberManageDetails.popupHide();
      } else if (this.$refs.memberManageFilterItem.popupVisible) {
        this.$refs.memberManageItem.back();
      } else {
        // if (this.$route.query.close == "true") {
        //   jsBridge.closeWindow();
        // } else {
        //   this.$router.back();
        // }
        jsBridge.closeWindow();
      }
    },
    loadData() {
      this.loading = true;
      let shopId = this.roleInfo.manyShopFlag? this.filterData.shopId:this.selfShopId;
      if (!shopId) {
        return;
      }
      if (this.pageIndex == 1) {
        this.list = [];
      }
      const searchKey =
        this.searchParam.id && this.searchParam.id.length > 0
          ? this.searchParam.id
          : "";
      this.ajax({
        url: `/mini/memberManage/list.do?shopId=${shopId}&currentPage=${this.pageIndex}&pageSize=${this.pageSize}&gender=${this.filterData.gender}&channelSource=${this.filterData.channelSource}&searchKey=${searchKey}`,
        type: "get",
        controlLoading: true,
      })
        .then(response => {
          this.loading = false;
          if (response.success) {
            let data = response.resultObject;
            if (data.dataList) {
              this.list = this.list.concat(data.dataList);
            }
            if (data.dataAllCount) {
              this.noMore = Math.ceil(data.dataAllCount / this.pageSize) === this.pageIndex ? true : false;
            } else {
              this.noMore = true;
            }

            this.pageIndex = this.pageIndex + 1;
          } else {
            this.noMore = true;
            Toast(response.msg);
          }
        })
        .catch(error => {
          this.loading = false;
          this.noMore = true;
        });
    },

    //无限加载
    loadMore() {
      if (this.loading || this.noMore || !this.role) {
        return;
      }
      this.loadData();
    },
    //是否订购会员管理
    getStatus() {
      //serviceCode 服务类型：9：小程序；10：会员服务
      this.ajax({
        url: "/applet/manager/queryYzProShopServiceModelByCondition.do?serviceCode=10",
        type: "get",
        controlLoading: false
      })
        .then(res => {
          if (res.success) {
            const status = res.resultObject;//小程序： 0:未开通 1:开启 2:停用 会员服务： 0:关闭 1:开启
            if (status === 1) {
              this.isOpen = true;
            } else {
              this.$router.push({ path: "/mallList/serviceProductDetails", query: { machineType: 19, close: true } });
            }
          } else {
            Toast(res.msg);
          }
        })
        .catch(function (err) {
  
        });
    },
    getShopList() {
      this.ajax({
        url: `/applet/manager/queryCityShopList.do?queryType=2&serviceCode=10`,
        type: "get",
        controlLoading: false
      })
        .then((res) => {
          if (res.success) {
            const data = res.resultObject;
            let shopList = [];
            if (data != null && JSON.stringify(data) != "{}") {
              for (var cityName in data) {
                if (data[cityName] != null && data[cityName].length > 0) {
                  for (var i = 0; i < data[cityName].length; i++) {
                    //未开通小程序或者不满足条件的门店（mini：已开通小程序 true:开通；  passMini：符合小程序开通 true:符合 false:不符合）
                    if (data[cityName][i]['passMini']) {
                      shopList.push({
                        shopId: data[cityName][i].shopId,
                        shopName: data[cityName][i].shopName,
                      });
                    }
                  }
                }
              }
            }

            if (shopList.length) {
              this.filterData.shopId = shopList[0].shopId;
              this.filterData.shopName = shopList[0].shopName;
              this.currentStore = [{ selectKey: shopList[0].shopId, selectName: shopList[0].shopName }];
              this.loadData();
            }
          }
        })
        .catch(function (err) {

        });
    },
  },
  created() {
    this.getStatus();
    CommonUtil.getUserInfo().then(userInfo => {
      this.role = userInfo.role;
      this.roleInfo = userInfo;
      this.selfShopId = userInfo.yzShopId;
      if (userInfo.manyShopFlag) {
        this.getShopList();
      } else {
        this.loadData();
      }

    });
  },

  computed: {},
  components: {
    customHeader,
    noData,
    searchBar,
    filterItem,
    memberManageDetails
  }
};
</script>
<style lang='scss' scoped>
@import "memberManage";
</style>
